<template>
  <view class="categories-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">风格类型管理</text>
      <button class="add-btn" @click="showAddModal">新增类型</button>
    </view>
    
    <!-- 分类列表 -->
    <view class="categories-list">
      <view class="list-header">
        <!-- <text class="header-item header-id">ID</text> -->
        <text class="header-item header-name">名称</text>
        <!-- <text class="header-item header-desc">描述</text> -->
        <text class="header-item header-sort">排序</text>
        <!-- <text class="header-item header-status">状态</text> -->
        <text class="header-item header-action">操作</text>
      </view>
      
      <view v-if="categories.length === 0" class="empty-tip">
        <text>暂无风格类型数据</text>
      </view>
      
      <view v-else class="list-content">
        <view v-for="(item, index) in categories" :key="item.id" class="list-item">
          <!-- <text class="item-id">{{ item.id }}</text> -->
          <text class="item-name">{{ item.name }}</text>
          <!-- <text class="item-desc">{{ item.description || '无' }}</text> -->
          <text class="item-sort">{{ item.sort }}</text>
          <!-- <view class="item-status">
            <view :class="['status-badge', item.status === 1 ? 'status-active' : 'status-inactive']">
              {{ item.status === 1 ? '启用' : '禁用' }}
            </view>
          </view> -->
          <view class="item-action">
            <button class="action-btn edit-btn" @click="editCategory(item)">编辑</button>
            <button class="action-btn status-btn" @click="toggleStatus(item)">
              {{ item.status === 1 ? '禁用' : '启用' }}
            </button>
            <button class="action-btn delete-btn" @click="confirmDelete(item)">删除</button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view v-if="categories.length > 0" class="load-more">
      <text v-if="loading">加载中...</text>
      <text v-else-if="!hasMore">没有更多数据了</text>
      <button v-else class="load-more-btn" @click="loadMoreCategories">加载更多</button>
    </view>
    
    <!-- 新增/编辑分类弹窗 -->
    <view v-if="showFormModal" class="modal-mask" @click="closePopup">
      <view class="modal-content" @click.stop>
        <view class="popup-title">{{ isEdit ? '编辑风格类型' : '新增风格类型' }}</view>
        
        <view class="form-item">
          <text class="form-label">名称</text>
          <input 
            class="form-input" 
            type="text" 
            v-model="formData.name" 
            placeholder="请输入类型名称"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">描述</text>
          <textarea 
            class="form-textarea" 
            v-model="formData.description" 
            placeholder="请输入类型描述"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">排序值</text>
          <input 
            class="form-input" 
            type="number" 
            v-model="formData.sort" 
            placeholder="请输入排序值（数字越小越靠前）"
          />
        </view>
        
        <view class="form-item">
          <text class="form-label">状态</text>
          <switch 
            :checked="formData.status === 1" 
            @change="handleStatusChange" 
            color="#FF69B4"
          />
        </view>
        
        <view class="form-actions">
          <button class="cancel-btn" @click="closePopup">取消</button>
          <button class="submit-btn" @click="submitForm">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 删除确认弹窗 -->
    <view v-if="showDeleteModal" class="modal-mask" @click="closeDeletePopup">
      <view class="modal-dialog" @click.stop>
        <view class="dialog-title">删除确认</view>
        <view class="dialog-content">确定要删除该风格类型吗？删除后无法恢复，且如果有风格使用了该类型将无法删除。</view>
        <view class="dialog-actions">
          <button class="cancel-btn" @click="closeDeletePopup">取消</button>
          <button class="confirm-btn" @click="deleteCategory">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { styleApi } from '@/utils/api.js';
import { formatDateTime  } from '../../utils/common';

export default {
  data() {
    return {
      // 分类列表数据
      categories: [],
      // 分页参数
      pageNum: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      
      // 弹窗控制
      showFormModal: false,
      showDeleteModal: false,
      isEdit: false,
      formData: {
        id: null,
        name: '',
        description: '',
        sort: 0,
        status: 1
      },
      
      // 删除确认弹窗
      currentCategory: {}
    };
  },
  
  onLoad() {
    this.checkAdminPermission();
    this.loadCategories();
  },
  
  methods: {
    // 检查管理员权限
    checkAdminPermission() {
      // const userInfo = uni.getStorageSync('userInfo');
      // if (!userInfo || userInfo.role !== 'admin') {
      //   uni.showToast({
      //     title: '您没有管理员权限',
      //     icon: 'none'
      //   });
      //   setTimeout(() => {
      //     uni.navigateBack();
      //   }, 1500);
      // }
    },
    
    // 加载风格分类列表
    loadCategories() {
      this.loading = true;
      
      styleApi.getAllStyleCategories().then(res => {
        if (res.code === 200) {
          this.categories = res.data || [];
          this.hasMore = false; // 一次性加载所有分类，不需要分页
        } else {
          uni.showToast({
            title: res.message || '加载失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('加载风格分类列表失败', err);
        uni.showToast({
          title: '加载失败，请检查网络',
          icon: 'none'
        });
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 加载更多分类（预留，目前一次性加载所有）
    loadMoreCategories() {
      if (this.hasMore && !this.loading) {
        this.pageNum++;
        this.loadCategories();
      }
    },
    
    // 显示新增分类弹窗
    showAddModal() {
      this.isEdit = false;
      this.formData = {
        id: null,
        name: '',
        description: '',
        sort: 0,
        status: 1
      };
      this.showFormModal = true;
    },
    
    // 编辑分类
    editCategory(item) {
      this.isEdit = true;
      this.formData = {
        id: item.id,
        name: item.name,
        description: item.description || '',
        sort: item.sort,
        status: item.status
      };
      this.showFormModal = true;
    },
    
    // 关闭弹窗
    closePopup() {
      this.showFormModal = false;
    },
    
    // 处理状态切换
    handleStatusChange(e) {
      this.formData.status = e.detail.value ? 1 : 0;
    },
    
    // 提交表单
    submitForm() {
      // 表单验证
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入类型名称',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: this.isEdit ? '保存中...' : '创建中...'
      });
      
      // 调用API保存分类
      const apiMethod = this.isEdit 
        ? styleApi.updateStyleCategory.bind(styleApi, this.formData.id, this.formData)
        : styleApi.createStyleCategory.bind(styleApi, this.formData);
      
      apiMethod().then(res => {
        if (res.code === 200) {
          uni.showToast({
            title: this.isEdit ? '保存成功' : '创建成功',
            icon: 'success'
          });
          this.closePopup();
          this.loadCategories(); // 重新加载分类列表
        } else {
          uni.showToast({
            title: res.message || (this.isEdit ? '保存失败' : '创建失败'),
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error(this.isEdit ? '保存分类失败' : '创建分类失败', err);
        uni.showToast({
          title: this.isEdit ? '保存失败，请检查网络' : '创建失败，请检查网络',
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
      });
    },
    
    // 切换分类状态
    toggleStatus(item) {
      const newStatus = item.status === 1 ? 0 : 1;
      const statusText = newStatus === 1 ? '启用' : '禁用';
      
      uni.showLoading({
        title: `${statusText}中...`
      });
      
      styleApi.updateStyleCategoryStatus(item.id, newStatus).then(res => {
        if (res.code === 200) {
          uni.showToast({
            title: `${statusText}成功`,
            icon: 'success'
          });
          // 更新本地数据
          const index = this.categories.findIndex(category => category.id === item.id);
          if (index !== -1) {
            this.categories[index].status = newStatus;
          }
        } else {
          uni.showToast({
            title: res.message || `${statusText}失败`,
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error(`${statusText}分类失败`, err);
        uni.showToast({
          title: `${statusText}失败，请检查网络`,
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
      });
    },
    
    // 确认删除
    confirmDelete(item) {
      this.currentCategory = item;
      this.showDeleteModal = true;
    },
    
    // 关闭删除确认弹窗
    closeDeletePopup() {
      this.showDeleteModal = false;
    },
    
    // 删除分类
    deleteCategory() {
      uni.showLoading({
        title: '删除中...'
      });
      
      styleApi.deleteStyleCategory(this.currentCategory.id).then(res => {
        if (res.code === 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          // 从列表中移除
          const index = this.categories.findIndex(category => category.id === this.currentCategory.id);
          if (index !== -1) {
            this.categories.splice(index, 1);
          }
        } else {
          uni.showToast({
            title: res.message || '删除失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('删除分类失败', err);
        uni.showToast({
          title: '删除失败，请检查网络',
          icon: 'none'
        });
      }).finally(() => {
        uni.hideLoading();
        this.closeDeletePopup();
      });
    }
  }
};
</script>

<style lang="scss">
.categories-container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .page-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
    
    .add-btn {
      background-color: #FF69B4;
      color: #fff;
      font-size: 28rpx;
      padding: 12rpx 30rpx;
      border-radius: 8rpx;
    }
  }
  
  .categories-list {
    background-color: #fff;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .list-header {
      display: flex;
      padding: 20rpx 0;
      background-color: #f6f6f6;
      font-weight: bold;
      font-size: 28rpx;
      color: #333;
      border-bottom: 1px solid #eee;
      
      .header-item {
        padding: 0 20rpx;
        text-align: center;
      }
      
      .header-id {
        flex: 0 0 100rpx;
      }
      
      .header-name {
        flex: 0 0 200rpx;
      }
      
      .header-desc {
        flex: 1;
      }
      
      .header-sort {
        flex: 0 0 100rpx;
      }
      
      .header-status {
        flex: 0 0 120rpx;
      }
      
      .header-action {
        flex: 0 0 280rpx;
      }
    }
    
    .empty-tip {
      padding: 60rpx 0;
      text-align: center;
      color: #999;
      font-size: 28rpx;
    }
    
    .list-content {
      .list-item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1px solid #eee;
        font-size: 28rpx;
        
        &:last-child {
          border-bottom: none;
        }
        
        .item-id {
          flex: 0 0 100rpx;
          padding: 0 20rpx;
          text-align: center;
          color: #666;
        }
        
        .item-name {
          flex: 0 0 200rpx;
          padding: 0 20rpx;
          text-align: center;
          color: #333;
          font-weight: 500;
        }
        
        .item-desc {
          flex: 1;
          padding: 0 20rpx;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .item-sort {
          flex: 0 0 100rpx;
          padding: 0 20rpx;
          text-align: center;
          color: #666;
        }
        
        .item-status {
          flex: 0 0 120rpx;
          padding: 0 20rpx;
          text-align: center;
          
          .status-badge {
            display: inline-block;
            padding: 4rpx 12rpx;
            border-radius: 6rpx;
            font-size: 24rpx;
          }
          
          .status-active {
            background-color: #e6f7e6;
            color: #52c41a;
          }
          
          .status-inactive {
            background-color: #f5f5f5;
            color: #999;
          }
        }
        
        .item-action {
          flex: 0 0 280rpx;
          padding: 0 20rpx;
          display: flex;
          justify-content: space-around;
          
          .action-btn {
            font-size: 24rpx;
            padding: 6rpx 12rpx;
            margin: 0 4rpx;
            border-radius: 6rpx;
          }
          
          .edit-btn {
            background-color: #1890ff;
            color: #fff;
          }
          
          .status-btn {
            background-color: #faad14;
            color: #fff;
          }
          
          .delete-btn {
            background-color: #ff4d4f;
            color: #fff;
          }
        }
      }
    }
  }
  
  .load-more {
    text-align: center;
    margin-top: 30rpx;
    color: #999;
    font-size: 28rpx;
    
    .load-more-btn {
      background-color: #fff;
      color: #666;
      font-size: 28rpx;
      padding: 12rpx 30rpx;
      border-radius: 8rpx;
      border: 1px solid #ddd;
    }
  }
  
  .popup-content {
    width: 600rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 30rpx;
      color: #333;
    }
    
    .form-item {
      margin-bottom: 20rpx;
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .form-input {
        width: 100%;
        height: 80rpx;
        border: 1px solid #ddd;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        box-sizing: border-box;
      }
      
      .form-textarea {
        width: 100%;
        height: 160rpx;
        border: 1px solid #ddd;
        border-radius: 8rpx;
        padding: 20rpx;
        font-size: 28rpx;
        box-sizing: border-box;
      }
    }
    
    .form-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      
      button {
        width: 45%;
        height: 80rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        line-height: 80rpx;
      }
      
      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }
      
      .submit-btn {
        background-color: #FF69B4;
        color: #fff;
      }
    }
  }
  
  .modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
  }
  
  .modal-content {
    width: 600rpx;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 30rpx;
      color: #333;
    }
    
    .form-item {
      margin-bottom: 25rpx;
      
      .form-label {
        display: block;
        margin-bottom: 10rpx;
        font-size: 28rpx;
        color: #666;
      }
      
      .form-input {
        width: 100%;
        height: 80rpx;
        border: 1rpx solid #e0e0e0;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        box-sizing: border-box;
      }
      
      .form-textarea {
        width: 100%;
        height: 160rpx;
        border: 1rpx solid #e0e0e0;
        border-radius: 8rpx;
        padding: 20rpx;
        font-size: 28rpx;
        box-sizing: border-box;
      }
    }
    
    .form-actions {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      
      button {
        width: 45%;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 28rpx;
        border-radius: 8rpx;
      }
      
      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }
      
      .submit-btn {
        background-color: #FF69B4;
        color: #fff;
      }
    }
  }
  
  .modal-dialog {
    width: 600rpx;
    background-color: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    
    .dialog-title {
      padding: 30rpx;
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      color: #333;
      border-bottom: 1rpx solid #f0f0f0;
    }
    
    .dialog-content {
      padding: 40rpx 30rpx;
      font-size: 28rpx;
      color: #666;
      text-align: center;
      line-height: 1.5;
    }
    
    .dialog-actions {
      display: flex;
      border-top: 1rpx solid #f0f0f0;
      
      button {
        flex: 1;
        height: 90rpx;
        line-height: 90rpx;
        font-size: 28rpx;
        border-radius: 0;
      }
      
      .cancel-btn {
        background-color: #fff;
        color: #666;
        border-right: 1rpx solid #f0f0f0;
      }
      
      .confirm-btn {
        background-color: #FF69B4;
        color: #fff;
      }
    }
  }
}
</style>
